package com.dream52.pms.config;


import com.dream52.pms.base.PmsConstant;
import com.dream52.pms.base.PmsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/** 全局exception拦截 ***/
@RestControllerAdvice
public class GlobalDefultExceptionHandler extends ResponseEntityExceptionHandler {
	
	private static final Logger log = LoggerFactory.getLogger(GlobalDefultExceptionHandler.class);
	
	// 声明要捕获的异常
	@ExceptionHandler(Exception.class)
	public Map<String, String> defultExcepitonHandler(HttpServletRequest request, Exception e) {
		String sOut = "后台exception：\r\n<br />异常类型："+e.toString();
		sOut += "<br />异常信息:\t"+e.getMessage()+"<br />明细：";
		StackTraceElement[] trace = e.getStackTrace();
		for (StackTraceElement s : trace) {
			sOut += "<br />" + s + "\r\n";
		}
		
		String requestStr = getRequestParameter(request);
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("retcode", PmsConstant.ERROR_CODE_999999.toString());
		map.put("retmsg", sOut);
		
		e.printStackTrace();
		
		log.error("\n捕获异常:"+ e.getMessage() +"\n"+ requestStr + sOut);
		
		return map;
	}
	
	/**
     * 拦截捕捉自定义异常 TwjException.class
     * @param ex
     * @return
     */
    @ExceptionHandler(value = PmsException.class)
    public Map<String, String> myErrorHandler(HttpServletRequest request, PmsException ex) {
    	String sOut = "\n后台exception：\r\n异常类型："+ex.toString();
		sOut += "\n异常信息:\t"+ex.getRetCode().toString()+"\t"+ex.getRetMsg()+"\n明细：";
		StackTraceElement[] trace = ex.getStackTrace();
		for (StackTraceElement s : trace) {
			sOut += "\n" + s + "\r";
		}
		
		String requestStr = getRequestParameter(request);
		
    	Map<String, String> map = new HashMap<String, String>();
        map.put("retcode", ex.getRetCode().toString());
        map.put("retmsg", ex.getRetMsg());
        
        ex.printStackTrace();
        
        
        log.error("\n捕获异常:"+ ex.getMessage() +"\n"+ requestStr + sOut);
        
        return map;
    }
    
    /**
     * 拿到request的参数并组装
     * @param request
     * @return
     */
    private String getRequestParameter(HttpServletRequest request){
    	String requestStr = "URL:";
		//URL
		String url = request.getRequestURL().toString();
		//传的参数
		Map<String, String[]> ParameterMap = request.getParameterMap();

		requestStr += url+"\n";
		String parameterStr = "";
		for (String key : ParameterMap.keySet()) {
             //map.keySet()返回的是所有key的值
             String[] str = ParameterMap.get(key);//得到每个key多对用value的值
			if (str.length > 0) {
				parameterStr +=key + ":" + str[0];
			}
         }
		
		requestStr += "参数：{"+parameterStr+"}";
		
		return requestStr;
    }

}
